package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.tbl.common.utils.*;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.entity.baseinfo.Material;
import com.tbl.modules.wms.service.baseinfo.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 物料清单控制层
 * @author 70486
 */
@Controller
@RequestMapping(value = "/materials")
public class MaterialController extends AbstractController {

    /**
     * 物料
     */
    @Autowired
    private MaterialService materialService;
    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;

    /**
     * 跳转到物料列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/baseinfo/materials/materials_list");
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.materials));
        return mv;
    }

    /**
     * 获取物料列表数据
     * @param queryJsonString 查询条件
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(3);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = materialService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 物料清单导出Excel
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            String sheetName = "物料清单" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String[] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length == 1 && "".equals(excelIndexArray[0])) {
                mapFields.put("code", "物料编码");
                mapFields.put("name", "物料名称");
            } else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("code", "物料编码");
                    } else if ("3".equals(s)) {
                        mapFields.put("name", "物料名称");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, materialService.getExcelList(request.getParameter("ids"), request.getParameter("queryName")),
                    mapFields, response, "");
            logService.logInsert("物料导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步物料基础数据
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/synchronousdata.do")
    @ResponseBody
    public Map<String, Object> synchronousdata() {
        //下面代码不能删除
        /*try {
            logger.info(DateUtils.getTime() + " >>同步物料基础数据....");
            Map<String, Object> xmlMap = new HashMap<>(1);
            xmlMap.put("line", new HashMap<String, Object>(2) {{
                put("materialno", "");
                put("materialname", "");
            }});
            wmsService.FEWMS001(xmlMap);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        Connection conn = JDBCUtils.getConnection();
        PreparedStatement pst = null;
        // 创建执行存储过程的对象
        CallableStatement proc = null;
        try {
            proc = conn.prepareCall("{ call EBS2WMS_YDDL_MATERIAL() }");
            // 执行
            proc.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭IO流
                proc.close();
                JDBCUtils.closeAll(null, pst, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new HashMap<String, Object>(2) {{
            put("result", true);
            put("msg", "更新成功！");
        }};
    }

    /**
     * 点击编辑，跳转到编辑页面
     * @param id 调拨单主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/edit.do")
    @ResponseBody
    public ModelAndView editInfo(Long id) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("material", materialService.selectInfoById(id));
        mv.setViewName("techbloom/baseinfo/materials/edit");
        return mv;
    }

    /**
     * 保存功能
     * @param material 物料信息
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/save.do")
    @ResponseBody
    public Map<String, Object> save(Material material) {
        materialService.updateById(material);
        Map<String, Object> map = new HashMap<>(3);
        map.put("result", true);
        map.put("msg", "保存成功！");
        map.put("material", material);
        return map;
    }

    /**
     * 根据物料编码获取物料信息
     * @param code 物料编码
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/code/{code}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMaterialByCode(@PathVariable("code") String code){
        Map<String,Object> map = new HashMap<>(1);
        if(StringUtils.isNotEmpty(code)){
            map.put("code",code);
        }
        return materialService.selectMaterialByCode(map);
    }


    /**
     * 根据物料编码获取物料信息-模糊查询
     * @param code 物料编码
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/codes/{code}",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMaterialsByCode(@PathVariable("code") String code){
        Map<String,Object> map = new HashMap<>(1);
        if(StringUtils.isNotEmpty(code)){
            map.put("code",code);
        }
        return materialService.getMaterialsByCode(map);
    }


    @RequestMapping(value = "/getMaterialPageByCode",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getMaterialPageByCode(@RequestParam("code") String code){
        Map<String,Object> paramMap = getAllParameter();
        paramMap.put("code",code);

        return materialService.getMaterialsPageByCode(paramMap);
    }

    /**
     * 获取行业区分列表信息 ：下拉框
     * @param queryString 查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getIndustry")
    @ResponseBody
    public Map<String, Object> getIndustry(String queryString, int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<>(7);
        PageTbl page = this.getPage();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString.toUpperCase());
        //获取列表信息 ：下拉框
        map.put("result", materialService.getIndustryList());
        return map;
    }

    /**
     * 获取物料类别区分列表信息 ：下拉框
     * @param queryString 查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getCategory")
    @ResponseBody
    public Map<String, Object> getCategory(String queryString, int pageSize, int pageNo, String industry) {
        Map<String, Object> map = new HashMap<>(7);
        PageTbl page = this.getPage();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString.toUpperCase());
        //获取列表信息 ：下拉框
        map.put("result", materialService.getCategoryList(industry));
        return map;
    }

    /**
     * 获取二级材料列表信息 ：下拉框
     * @param queryString 查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getGradeTwo")
    @ResponseBody
    public Map<String, Object> getGradeTwo(String queryString, int pageSize, int pageNo, String industry, String category) {
        Map<String, Object> map = new HashMap<>(7);
        PageTbl page = this.getPage();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString.toUpperCase());
        //获取列表信息 ：下拉框
        map.put("result", materialService.getGradeTwoList(industry,category));
        return map;
    }

    /**
     * 获取三级材料列表信息 ：下拉框
     * @param queryString 查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getGradeThree")
    @ResponseBody
    public Map<String, Object> getGradeThree(String queryString, int pageSize, int pageNo, String industry, String category, String grateTwo) {
        Map<String, Object> map = new HashMap<>(7);
        PageTbl page = this.getPage();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString.toUpperCase());
        //获取列表信息 ：下拉框
        map.put("result", materialService.getGradeThreeList(industry, category, grateTwo));
        return map;
    }
}
